#include "dirStack.h"

void _dirStack_init(_dirStack_t* s) {
    bzero(s->_stack, 1024 * sizeof(char*));
    s->_top = -1;
}

bool _dirStack_empty(_dirStack_t* s){
    return s->_top == -1;
}

int _dirStack_push(_dirStack_t* s, char* token){
    char* tmp = (char*)calloc(strlen(token), sizeof(char));
    ERROR_CHECK(tmp, NULL, "_dirStack_push calloc");
    strncpy(tmp, token, strlen(token));
    s->_stack[++s->_top] = tmp;
    return 0;
}

int _dirStack_pop(_dirStack_t* s){
    if(_dirStack_empty(s)){
        fprintf(stderr, "pop in empty stack.\n");
        return 1;
    }
    free(s->_stack[s->_top]);
    s->_stack[s->_top] = NULL;  
    --s->_top;
    return 0;
}

char* _dirStack_top(_dirStack_t* s){
    if(_dirStack_empty(s)){
        fprintf(stderr, "get top from empty stack.\n");
        return NULL;
    }
    return s->_stack[s->_top];
}

char* _dirStack_getDir(_dirStack_t* s){
    char* str = (char*)calloc(4096, sizeof(char));
    int n = s->_top;
    for(int i = 0;i <= n; ++i){
        strcat(str, s->_stack[i]);
        strcat(str, "/");
    }
    return str;
}

int _dirStack_copy(_dirStack_t *dest, const _dirStack_t *src)
{
	dest->_top = src->_top;
	for (int i = 0; i <= src->_top; ++i) {
		if (src->_stack[i] == NULL) {
			dest->_stack[i] = NULL;
		}
		dest->_stack[i] = strdup(src->_stack[i]);
	}
	return 1;
}

/* void test_dirStack() { */
/*     _dirStack_t stack; */
/*     _dirStack_init(&stack); */

/*     printf("Test: Initialize Stack\n"); */
/*     printf("Expected: Stack should be empty\n"); */
/*     printf("Result: %s\n", _dirStack_empty(&stack) ? "Empty" : "Not Empty"); */

/*     printf("\nTest: Push elements onto Stack\n"); */
/*     _dirStack_push(&stack, "folder1"); */
/*     _dirStack_push(&stack, "folder2"); */
/*     _dirStack_push(&stack, "folder3"); */

/*     printf("Expected: Stack should not be empty\n"); */
/*     printf("Result: %s\n", _dirStack_empty(&stack) ? "Empty" : "Not Empty"); */

/*     printf("\nTest: Get top element\n"); */
/*     printf("Expected: folder3\n"); */
/*     printf("Result: %s\n", _dirStack_top(&stack)); */

/*     printf("\nTest: Pop top element\n"); */
/*     _dirStack_pop(&stack); */
/*     printf("Expected: folder2\n"); */
/*     printf("Result: %s\n", _dirStack_top(&stack)); */

/*     printf("\nTest: Pop remaining elements\n"); */
/*     _dirStack_pop(&stack); */
/*     _dirStack_pop(&stack); */

/*     printf("Expected: Stack should be empty\n"); */
/*     printf("Result: %s\n", _dirStack_empty(&stack) ? "Empty" : "Not Empty"); */

/*     printf("\nTest: Pop from empty stack\n"); */
/*     printf("Expected: Error message\n"); */
/*     _dirStack_pop(&stack); */
/* } */

/* int main() { */
/*     test_dirStack(); */
/*     return 0; */
/* } */
